package com.dl.test.config;

import com.dl.test.interceptor.MybatisInterceptor;
import com.github.pagehelper.PageInterceptor;
import com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration;
import com.github.pagehelper.autoconfigure.PageHelperProperties;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author DL
 * @create 2022-08-29 17:46
 */
@Slf4j
@Configuration
@AutoConfigureAfter({MybatisAutoConfiguration.class})
@EnableConfigurationProperties({PageHelperProperties.class})
@EnableAutoConfiguration(exclude = {PageHelperAutoConfiguration.class})
public class GlobalMybatisConfig implements InitializingBean {

    //Construction > 对象属性set() 方法-> @PostConstruct -> InitializingBean -> initMethod

    @Resource
    private List<SqlSessionFactory> sqlSessionFactoryList;

    /**
     * pageInterceptor配置参数
     */
    @Resource
    private PageHelperProperties properties;

    @Resource
    private MybatisInterceptor mybatisInterceptor;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("afterPropertiesSet执行");
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(properties);
        log.info("properties:{} ", properties);
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            // 将自定义的拦截器放在pageHelper的拦截器后面，后面的先执行，就可以避免因为pageInterceptor直接return导致自定义拦截器失效问题
            sqlSessionFactory.getConfiguration().addInterceptor(pageInterceptor);
            sqlSessionFactory.getConfiguration().addInterceptor(mybatisInterceptor);
        }
    }
}
